#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

typedef struct Usr
{
	int iId;
	char caName[32];
	int iAge;
	float fMoney;

	struct Usr *next;
}Usr;

typedef struct List
{
	int iLen;
	Usr *pFirstNode;
}List;

Usr *mkUsrNode()
{
	Usr *node = (Usr*)malloc(sizeof(Usr));
	if (NULL == node)
	{
		exit(EXIT_FAILURE);
	}
	memset(node, 0, sizeof(Usr));
	return node;
}

List *mkList()
{
	List *list = (List*)malloc(sizeof(List));
	if (NULL == list)
	{
		exit(EXIT_FAILURE);
	}
	memset(list, 0, sizeof(List));
	return list;
}

void insert(List *list, Usr *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}
	node->next = list->pFirstNode;
	list->pFirstNode = node;	
	list->iLen++;
}

void display(const List *list)
{
	if (NULL == list)
	{
		return;
	}

	Usr *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("id=%d,name=%s,age=%d,money=%.1f\n"
			   , node->iId, node->caName, node->iAge
			   , node->fMoney);
		node = node->next;
	}
}

void input(Usr *node)
{
	if (NULL == node)
	{
		return;
	}
	printf("请输入人员信息id,name,age,money:\n");
	scanf("%d%s%d%f", &node->iId, node->caName
					, &node->iAge, &node->fMoney);
}

void swapNode(Usr *n1, Usr *n2)
{
	Usr *nn1 = n1->next;
	Usr *nn2 = n2->next;
	Usr tmp = *n1;
	*n1 = *n2;
	*n2 = tmp;
	n1->next = nn1;
	n2->next = nn2;
}

void sortByAge(List *list)
{
	if (NULL == list)
	{
		return;
	}
	Usr *node = NULL;
	int i=0;
	int j=0;
	for (; i<list->iLen; i++)
	{
		node = list->pFirstNode;
		for (j=0; j<list->iLen-1; j++)
		{
			if (node->iAge > node->next->iAge)
			{
				swapNode(node, node->next);	
			}	
			node = node->next;
		}
	}
}

int main(int argc, char *argv[])
{	
	List *list = mkList();
	Usr *node = NULL;

	int i = 0;
	for (; i<5; i++)
	{
		node = mkUsrNode();
		input(node);
		insert(list, node);
	}
	display(list);
	sortByAge(list);
	printf("----------------------\n\n");
	display(list);

	return 0;
}
